package com.wanxi.filter;

import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author 杨金乾
 */
@WebFilter("/*")
@Component
public class CharacterFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        Filter.super.init(filterConfig);
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request= (HttpServletRequest) servletRequest;
        HttpServletResponse response= (HttpServletResponse) servletResponse;
        //获取客户端请求路径
        String url = request.getRequestURL().toString();
        //后端静态资源及站点根路径不要字符集处理，直接放行。
        if(url.endsWith(".html") || url.endsWith(".css") || url.endsWith(".js")
                || url.endsWith(".png") || url.endsWith(".jpg") || url.endsWith(".jpeg")
                || url.endsWith(".gif") || "/".equals(request.getRequestURI())){
            filterChain.doFilter(request, response);
            return;
        }
        /*
         * 解决servlet乱码
         * */
        //解决请求参数的乱码
        request.setCharacterEncoding("utf-8");
        //解决服务端响应数据的乱码
        response.setCharacterEncoding("utf-8");
        //解决服务端返回文本及html的乱码。
        response.setHeader("Content-Type","text/html;charset=UTF-8");
        filterChain.doFilter(request, response);
    }

    @Override
    public void destroy() {
        Filter.super.destroy();
    }
}
